<?php
/* $Id: common.php 20 2009-12-04 22:50:33Z ronan $ */
//BEGIN GLOBAL VARIABLES
$browser = $_SERVER['HTTP_USER_AGENT'];
$ingame = (substr($browser,-7,7)=='EVE-IGB'); 
require("config.php");
//Set per-category specific fields - users has a password field that needs special attention, and
// both users and orders have enum fields that need special attention.
// These are used in the to the toEditableTableRow function.
$passwordkeys=array("password"=>'');
$enumkeys=array("userlevel"=>array('user', 'producer', 'admin', 'trader', 'producertrader'), "status"=>array('in cart', 'awaiting producer', 'in queue', 'in production', 'on contract', 'completed', 'awaiting processing', 'being processed'));
//Set definitions for tables' primary keys
$idkeylist=array("items"=>"typeID", "users"=>"id", "orders"=>"id", "blueprints"=>"id", "minerals"=>"typeID");
//Global temps used in table creation
$bgcolor=false;
$bgcolored=false;
//Sizes of images in browse window

$imgsizegroup = 32;

//Default dateTime settings (see php date() function to make heads/tails of it)
$dateFormat="n\/j\/y";
$timeFormat="H\:i";
$dateTimeFormat="H\:i n\/j\/y";
//Timezones as offset from GMT - use these to make everything properly evetime
$eveTimeZone=0;
$serverTimeZone=-5;
//This regex is used to test whether an email address is valid.
$emailRegex = "/^([a-zA-Z0-9])+([\.+a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$/";
//Maximum amount that can be ordered.
$maxQuantity = 21000000;

//END GLOBAL VARIABLES

//BEGIN GLOBAL FUNCTIONS
function is_alphanumeric($test) {
    return (preg_match("/^[a-z0-9 ]+$/i", $test));
}
function is_number($number)
{
    $text = (string)$number;
    $textlen = strlen($text);
    if ($textlen==0) return 0;
    for ($i=0;$i < $textlen;$i++)
    { $ch = ord($text{$i});
    if (($ch<48) || ($ch>57)) return 0;
    }
    return 1;
}
function addCommas($number) {
    $broken_number = explode(".",$number);
    if(empty($broken_number[1])){
        return number_format($broken_number[0],0,'.',',');
    }else{
        return number_format($number,2,'.',',');
    }
}
function stripCommas($number) {
    return str_replace(",","",$number);
}
//For password resetting
function generatePassword($length=12) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
    $code = "";
    while (strlen($code) < $length) {
        $code .= $chars[mt_rand(0,strlen($chars))];
    }
    return $code;
}
function __construct($urlIn)
        {
                $this->claimsUrl = $urlIn;
        }

        /*
         * Attempt to gain trust from the client.
         * May cause a page reload.
         */

function GetTrust() {
    global $trusted, $host;
        if ($_SERVER['HTTP_EVE_TRUSTED']=='no') {
            // request trust from client through headers and quit unless we have it
//           header("eve.trustme:"."http://".$_SERVER['HTTP_HOST']."/::This site must be trusted for the tool to function.");
?>
                                        <body bgcolor="black">
                                                <script type="text/javascript">
                                                        CCPEVE.requestTrust('<? echo $this->claimsUrl; ?>');
                                                </script>
                                                <center>
                                                        <button type="button" onclick="window.location.reload()">Trust me (<? echo $this->claimsUrl; ?>) and then click here</button>
                                                </center>
                                <?
            quit("This area of the site requires trust.");
            $trusted = false;
        } else {
            $trusted = true;
        }
}
function InitCharData() {
    global $trusted;
    if($trusted) {
        global $pilotname, $pilotcorp, $pilotalliance, $isTGRAD;
        $pilotname = $_SERVER['HTTP_EVE_CHARNAME'];
        $pilotcorp = $_SERVER['HTTP_EVE_CORPNAME'];
        $pilotalliance = $_SERVER['HTTP_EVE_ALLIANCENAME'];
//        $isBRUCE=(283331937==$_SERVER['HTTP_EVE_ALLIANCEID']);
        $isTGRAD=('The Graduates'==$_SERVER['HTTP_EVE_CORPNAME']);
    }
}
function Query($q) {
    global $host, $dbuser, $dbpassword, $dbname;
    if(!mysql_connect($host,$dbuser,$dbpassword)) quit("Unable to connect to MySQL");
    @mysql_select_db($dbname) or die( "Unable to select database");
    $r=mysql_query($q);
    mysql_close();
    return $r;
}
function getGraphicPath($gfx) 
{
	//parent group ID's of all the games charges
	$chargeID = array("848", "845");
	
    if(substr($gfx,2,1)=='_')
	{
		$gfx='itemimg/icons/'.$gfx.'.png';
	}
    else if($gfx=='')
	{
		$gfx='itemimg/icons/07_15.png';
	}
    else 
	{

		$gfx='http://image.eveonline.com/InventoryType/'.$gfx.'_64.png';
		
	}
    return $gfx;
}

function getImgsize($typeID)
{
	
	
    if(substr($typeID,2,1)=='_')
	{
		$imgsize=32;
	}
    else if($typeID=='')
	{
		$imgsize=32;
	}
    else 
	{
		$name = mysql_result(Query("SELECT typeName FROM items WHERE typeID=$typeID"),0,'typeName');
		$marketGroupID = mysql_result(Query("SELECT marketGroupID FROM items WHERE typeID=$typeID"),0,'marketGroupID');
		$parentGroupID = mysql_result(Query("SELECT parentGroupID FROM ccp_invmarketgroups WHERE marketGroupID=$marketGroupID"),0,'parentGroupID');
		//echo $name . "  " . $marketGroupID . "  " . $parentGroupID . "<br>";
		
		$chargeID = array("11", "114", "115", "117", "118", "387", "580", "581", "845", "846", "847", "848", "849", "850", "851", "852", "853", "850", "657", "968", "990");
		
		for ($i = 0; $i < count($chargeID); ++$i) 
		{
			if($parentGroupID == $chargeID[$i])
			{
				$imgsize = 32;
				return $imgsize;
			}
			else
			{
				$imgsize = 32;
			}
		}
	}
    return $imgsize;
}
function IGBAuthorize() {
    GetTrust();
    InitCharData();
//    global $ingame;
//    if(!$ingame) die("This area of the site requires you to be using the In Game Browser.");
    global $trusted;
    if(!$trusted) die("This tool requires trust.");
    global $isTGRAD;
    if(!$isTGRAD) die("You are not a member of TGRAD and are not authorized to use this tool.");
}
function quit($msg) {
    include_once("common.php");
    include_once("auth.php");
    include("header.php");
    echo $msg;
    include("footer.php");
    exit;
}
function displayAvailability($numAvailable, $isBuildable, $isSpecialOrderable) {
    if($numAvailable>0) {
        if(!$isSpecialOrderable) return '<font color="green">In Stock:</font> <b>'.addCommas($numAvailable).'</b><br /><font color="red">Stock Only</font>';
        else if($isBuildable) return '<font color="green">In Stock:</font> <b>'.addCommas($numAvailable).'</b><br />Buildable';
        else return '<font color="green">In Stock:</font> <b>'.addCommas($numAvailable).'</b><br /><font color="yellow">Can Special Order</font>';
    }
    else if(!$isSpecialOrderable && !$isBuildable) return '<font color="red">Cannot Order</font>';
    else if($isBuildable==0) return '<font color="red">Out of Stock</font><br /><font color="yellow">Can Special Order</font>';
    else return 'Built on Demand';
}
function isBuildableMarketTree($marketGroupID) {
    $cmid = $marketGroupID;
    while($cmid!="NULL" && $cmid!="") {
        //DO NOT CHANGE. Correct table. 
        $mg = Query("SELECT * FROM invMarketGroups WHERE marketGroupID='$cmid' LIMIT 1");
        if(mysql_result($mg, 0, 'isBuildable')==0) return 0;
        $cmid=mysql_result($mg,0,'parentGroupID');
    }
    return 1;
}
function toTableHeader($cat){
    //if(!is_array($sa)) return "<table border=0 cellspacing=0 cellpadding=2><tr><td>No field data</td></tr>\n";
    $r = "<table border=0 cellspacing=0 cellpadding=2><tr>";
    $fields=array();
    $dqueryr=Query("DESC $cat");
    while($line = mysql_fetch_array($dqueryr)) {
        $fields[$line['Field']]='';
    }
    foreach($fields as $key=>$col) {
        $r.="\t<td><b>$key</b></td>\t";
    }
    $r.="</tr>\n";
    return $r;
}
function toTableFooter(){
    return "</table>\n";
}

function toEditableTableHeader($sa, $flags=null, $add=false, $idkey=null){
    if(!is_array($sa)) return "<table border=0 cellspacing=0 cellpadding=2><tr><td>No field data</td></tr>\n";
    $r = "<form method=\"POST\" action=\"".$_SERVER['PHP_SELF']."\">";
    if(isset($flags)&&is_array($flags)) {
        foreach($flags as $key=>$flag) {
            $r.="<input type=\"hidden\" name=\"$key\" value=\"$flag\" />";
        }
    }
    $r.= "<table border=0 cellspacing=0 cellpadding=2><tr>";
    foreach($sa as $key=>$col) {
        if($add) if($key==$idkey) continue;
        $r.="\t<td><b>$key</b></td>\t";
    }
    $r.="</tr>\n";
    return $r;
}
function toEditableTableFooter($value="Save all"){
    return "</table><input type=\"submit\" value=\"$value\" /></form>";
}
//If rowindex is set, it's assumed that the whole table is editable - so it doesn't open/close the form itself
//If you set a password key, it sets it up to not display a value there
//For enum type fields use the following as an argument example:
//	array("userLevel"=>array("user", "producer", "admin"))
function toEditableTableRow($sa, $idkey, $edittype, $rowindex= -1, $add=false) {
    if(!is_array($sa)) return "<table border=0 cellspacing=0 cellpadding=2><tr><td>No row data</td></tr>\n";
    global $passwordkeys, $enumkeys, $bgcolor;
    $pre=$rowindex.'_';
    $r=($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">"); $bgcolor= !$bgcolor;
    $end="</tr>";
    foreach($sa as $key=>$col) {
        if($idkey==$key) {
            if($add) continue;
            $r.="\t<td><input type=\"hidden\" name=\"".$pre.$key."\" value=\"$col\"><a href=\"".$_SERVER['PHP_SELF'].'?f='.$edittype.'&id='.$col."\">$col</a></td>\t";
        }else if(array_key_exists($key, $passwordkeys)) {
            $r.="\t<td><input size=\"15\" type=\"password\" name=\"".$pre.$key."\" value=\"\" /></td>\t";
        }else if(array_key_exists($key, $enumkeys)){
            $k = $enumkeys[$key];
            $r.="\t<td><select name=\"".$pre.$key."\">";
            foreach($k as $v) {
                $r.='<option value="'.$v.'"'.($col==$v?' selected':'').'>'.$v.'</option>';
            }
            $r.="</select></td>\t";
        }else {
            $r.="\t<td><input size=\"".(!$add?(strlen($col)+2):15)."\" type=\"text\" name=\"".$pre.$key."\" value=\"".$col."\" /></td>\t";
        }
    }
    $r.= $end."\n";
    return $r;
}
function toTableRow($sa, $cat, $del=false) {
    if(!is_array($sa)) return "<tr><td>No row data</td></tr>\n";
    global $idkeylist;
    $idkey=$idkeylist[$cat];
    global $bgcolor;
    $r=($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">"); $bgcolor= !$bgcolor;
    foreach($sa as $key=>$col) {
        if($idkey==$key) {
            $r.="\t<td><a href=\"".$_SERVER['PHP_SELF'].'?f=edit&cat='.$cat.'&id='.$col."\">$col</a></td>\t";
        }else {$r.="\t<td>$col</td>\t";}
    }
    if($del) $r.="\t<td><a href=\"".$_SERVER['PHP_SELF']."?f=delete&cat=$cat&id=".$sa[$idkey]."\"><font color=\"red\">DEL</font></a></td>\t";
    $r.="\t</tr>\n";
    return $r;
}

function generateHiddenFields($flags){
    $r='';
    if(isset($flags)&& is_array($flags)) {
        foreach($flags as $n=>$v) {
            $r.='<input type="hidden" name="'.$n.'" value="'.$v.'" />';
        }
    }
    return $r;
}
//Generates a form consisting of just hidden inputs for the flags array and a button. Sends to self
function generateButton($value="Submit", $method="POST", $flags=null) {
    $r='<form action="'.$_SERVER['PHP_SELF'].'" method='.$method.'>';
    $r.=generateHiddenFields($flags);
    $r.='<input type="submit" value="'.$value.'" /></form>';
    return $r;
}

function toDate($datetime) { //not done, unsure if will need
    return $datetime;
}
function prevStage($cur) {
    switch ($cur) {
        case 'in cart':
            return 'in cart';
        case 'awaiting producer':
            return 'in cart';
        case 'in queue':
            return 'awaiting producer';
        case 'in production':
            return 'in queue';
        case 'produced':
            return 'in production';
        case 'on contract':
            return 'produced';
        case 'awaiting processing':
            return 'in cart';
        case 'being processed':
            return 'awaiting processing';
        case 'completed':
            return 'on contract';
    }
    return false;
}
function nextStage($cur) {
    switch ($cur) {
        case 'in cart':
            return 'awaiting producer';
        case 'awaiting producer':
            return 'in queue';
        case 'in queue':
            return 'in production';
        case 'in production':
            return 'produced';
        case 'produced':
            return 'on contract';
        case 'on contract':
            return 'completed';
        case 'awaiting processing':
            return 'being processed';
        case 'being processed':
            return 'on contract';
        case 'completed':
            return 'completed';
    }
    return false;
}
function getMarketPath($marketGroup=null, $isAdmin=false) {
    if(isset($marketGroup) && !is_number($marketGroup) && !($marketGroup=='all')) {echo "ERROR: INVALID MARKETGROUP"; require("footer.php"); exit;}
    if(isset($marketGroup)&&$marketGroup!='') {
        $origMarketGroup=Query("SELECT * FROM ccp_invMarketGroups WHERE marketGroupID='$marketGroup' LIMIT 1");
        $r=mysql_result($origMarketGroup, 0, 'marketGroupName');
        $p=mysql_result($origMarketGroup, 0, 'parentGroupID');
        $DEBUG = 0;
        while($p!='' && $DEBUG<10) {
            $mg = Query("SELECT * FROM ccp_invMarketGroups WHERE marketGroupID='$p' LIMIT 1");
            $r="<a href=\"".$_SERVER['PHP_SELF'].'?'.($isAdmin?'f=view&cat=items&':'').'marketgroup='.mysql_result($mg, 0,'marketGroupID')."&hastypes=0\">" . mysql_result($mg,0,'marketGroupName').'</a> >> '.$r;
            $p=mysql_result($mg,0,'parentGroupID');
            $DEBUG++;
        }
        $r="<a href=\"".$_SERVER['PHP_SELF'].($isAdmin?'?f=view&cat=items&':'').'">Index</a> >> '.$r;
        return $r;
    } else return "Index";
}
function getBlueprintMarketPath($marketGroup=null, $isAdmin=false) {
    if(isset($marketGroup) && !is_number($marketGroup) && !($marketGroup=='all')) {echo "ERROR: INVALID MARKETGROUP"; require("footer.php"); exit;}
    if(isset($marketGroup)&&$marketGroup!='') {
        if($marketGroup=='all') return "All";
        $origMarketGroup=Query("SELECT * FROM ccp_invMarketGroups WHERE marketGroupID='$marketGroup' LIMIT 1");
        $r=mysql_result($origMarketGroup, 0, 'marketGroupName');
        $p=mysql_result($origMarketGroup, 0, 'parentGroupID');
        $DEBUG = 0;
        while($p!='' && $DEBUG<10) {
            $mg = Query("SELECT * FROM ccp_invMarketGroups WHERE marketGroupID='$p' LIMIT 1");
            $r="<a href=\"".$_SERVER['PHP_SELF'].'?'.($isAdmin?'f=add&cat=blueprints&':'f=blueprints&').'marketgroup='.mysql_result($mg, 0,'marketGroupID')."&hastypes=0\">" . mysql_result($mg,0,'marketGroupName').'</a> >> '.$r;
            $p=mysql_result($mg,0,'parentGroupID');
            $DEBUG++;
        }
        //$r="<a href=\"".$_SERVER['PHP_SELF'].($isAdmin?'?f=view&cat=items&':'').'">Index</a> >> '.$r;
        return $r;
    } else return getBlueprintMarketPath(2,$isAdmin);
}

function getBlueprintMarketGroup($marketGroup, $isItemGroup=null, $isAdmin=false) {
    global $bgcolored, $imgsize;
    if(empty($marketGroup)) return getBlueprintMarketGroup(2,$isItemGroup,$isAdmin);
    if(!is_number($marketGroup) && !($marketGroup=='all')) {echo "ERROR: INVALID MARKETGROUP"; require("footer.php"); exit;}
    if(!isset($isItemGroup)) {
        $isItemGroup = mysql_result(Query("SELECT hasTypes FROM ccp_invMarketGroups WHERE marketGroupID=$marketGroup"),0,'hasTypes');
    }
    if(!is_number($isItemGroup)) {echo "ERROR: INVALID HASTYPES"; require("footer.php"); exit;}
    if($isItemGroup || $marketGroup=='all'){
        return getBlueprintItemGroup($marketGroup, $isAdmin);
    }
    if($isAdmin){
        $qryString = "SELECT ccpIMG.marketGroupID,ccpIMG.parentGroupID,ccpIMG.marketGroupName,ccpIMG.description,ccpEG.graphicID,ccpIMG.hasTypes,tgIMG.isBuildable,tgIMG.priceMod ".
			"FROM ccp_invMarketGroups as ccpIMG " .
			"left join invMarketGroups as tgIMG on tgIMG.marketGroupID = ccpIMG.marketGroupID ".
			"left join ccp_eveGraphics as ccpEG on ccpIMG.graphicID = ccpEG.graphicID ".
        	"WHERE ccpIMG.parentGroupID".(isset($marketGroup)?"='$marketGroup'":' IS NULL').
			" ORDER BY ccpIMG.marketGroupName ASC";
        echo $qyrString;
        $groups = Query($qryString);
    } else {
        $groups = Query("SELECT ccpIMG.marketGroupID,ccpIMG.parentGroupID,ccpIMG.marketGroupName,ccpIMG.description,ccpEG.graphicID,ccpIMG.hasTypes,tgIMG.isBuildable,tgIMG.priceMod ".
			"FROM ccp_invMarketGroups as ccpIMG " .
			"left join invMarketGroups as tgIMG on tgIMG.marketGroupID = ccpIMG.marketGroupID ".
			"left join ccp_eveGraphics as ccpEG on ccpIMG.graphicID = ccpEG.graphicID ".
        	"WHERE ccpIMG.parentGroupID".(isset($marketGroup)?"='$marketGroup'":' IS NULL').
        	" AND tgIMG.isBuildable='1'".
			" ORDER BY ccpIMG.marketGroupName ASC");
    }
    if(!mysql_num_rows($groups)) return "No groups are available in this category!<br />\n";
    $r= "<table border=0 cellspacing=0 cellpadding=2>\n";
    while ($l = mysql_fetch_array($groups, MYSQL_ASSOC)) {
        $typeID=$l['typeID'];
		$gfx=getGraphicPath($typeID);
		$imgsize=getImgsize($typeID);
        $r.=($bgcolored?"<tr class=\"marketgrouptablecolor1\">":"<tr class=\"marketgrouptablecolor2\">"); $bgcolored= !$bgcolored;
        $r .= 	"<!--ID: ".$l['marketGroupID']."-->\t" .
			"<td><a href=\"".$_SERVER['PHP_SELF'].'?'.($isAdmin?'f=add&cat=blueprints&':'f=blueprints&').'marketgroup='.$l['marketGroupID'].'&hastypes='.$l['hasTypes']."\">" .
				"<img width=\"$imgsize\" border=\"0\" height=\"$imgsize\" src=\"$gfx\" /></a></td>\t" .
			"<td><a href=\"".$_SERVER['PHP_SELF'].'?'.($isAdmin?'f=add&cat=blueprints&':'f=blueprints&').'marketgroup='.$l['marketGroupID'].'&hastypes='.$l['hasTypes']."\">".$l['marketGroupName']."</a></td>\t" .
			"<td>".$l['description']."</td>\t";
        if($isAdmin) $r .= "<td>".($l['isBuildable']?'<font color="green">Buildable</font>':'<font color="red">Un-Buildable</font>')." - <a href=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=0&id=".$l['marketGroupID']."&updatebuildable=1&isbuildable=".$l['isBuildable']."\">Set to ".($l['isBuildable']?'Un-':'')."Buildable</a></td>\t";
        $r.="</tr>\n";
    }
    $r.= "</table>";
    return $r;
}
function getMarketGroup($marketGroup, $isItemGroup=null, $isAdmin=false) {
    global $bgcolored, $imgsizegroup;
    if(isset($marketGroup) && !is_number($marketGroup)) {echo "ERROR: INVALID MARKETGROUP"; require("footer.php"); exit;}
    if(!isset($marketGroup)) $isItemGroup=0;
    if(!isset($isItemGroup)){
        $isItemGroup = mysql_result(Query("SELECT hasTypes FROM ccp_invMarketGroups WHERE marketGroupID=$marketGroup"),0,'hasTypes');
    }
    if(!is_number($isItemGroup)) {
        echo "ERROR: INVALID HASTYPES";
        require("footer.php");
        exit;
    }
    if($isItemGroup) {
        return getItemGroup($marketGroup, $isAdmin);
    }

    if($isAdmin){
        $qryString = "SELECT ccpIMG.marketGroupID,ccpIMG.parentGroupID,ccpIMG.marketGroupName,ccpIMG.description,ccpEG.icon,ccpIMG.hasTypes,tgIMG.isBuildable,tgIMG.priceMod ".
			"FROM ccp_invMarketGroups as ccpIMG " .
			"left join invMarketGroups as tgIMG on tgIMG.marketGroupID = ccpIMG.marketGroupID ".
			"left join ccp_eveGraphics as ccpEG on ccpIMG.graphicID = ccpEG.graphicID ".
        	"WHERE ccpIMG.parentGroupID".(isset($marketGroup)?"='$marketGroup'":' IS NULL').
			" ORDER BY ccpIMG.marketGroupName ASC";
        echo $qyrString;
        $groups = Query($qryString);
    } else {
        $groups = Query("SELECT ccpIMG.marketGroupID,ccpIMG.parentGroupID,ccpIMG.marketGroupName,ccpIMG.description,ccpEG.icon,ccpIMG.hasTypes,tgIMG.isBuildable,tgIMG.priceMod ".
			"FROM ccp_invMarketGroups as ccpIMG " .
			"left join invMarketGroups as tgIMG on tgIMG.marketGroupID = ccpIMG.marketGroupID ".
			"left join ccp_eveGraphics as ccpEG on ccpIMG.graphicID = ccpEG.graphicID ".
        	"WHERE ccpIMG.parentGroupID".(isset($marketGroup)?"='$marketGroup'":' IS NULL').
        	" AND tgIMG.isBuildable='1'".
			" ORDER BY ccpIMG.marketGroupName ASC");
    }
    if(!mysql_num_rows($groups)) return "No groups are available in this category!<br />\n";
    $r= "<table border=0 cellspacing=0 cellpadding=2>\n";
    while ($l = mysql_fetch_array($groups, MYSQL_ASSOC)) {
		//graphic for market groups
        $gfx=$l['icon'];
        if(substr($gfx,2,1)=='_') $gfx='itemimg/icons/'.$gfx.'.png';
        else if($gfx=='') $gfx='itemimg/icons/07_15.png';
        else $gfx='http://image.eveonline.com/InventoryType/'.$gfx.'_64.png';
        $r.=($bgcolored?"<tr class=\"marketgrouptablecolor1\">":"<tr class=\"marketgrouptablecolor2\">"); $bgcolored= !$bgcolored;
        $r .= 	"<!--ID: ".$l['marketGroupID']."-->\t" .
			"<td><a href=\"".$_SERVER['PHP_SELF'].'?'.($isAdmin?'f=view&cat=items&':'').'marketgroup='.$l['marketGroupID'].'&hastypes='.$l['hasTypes']."\">" .
				"<img width=\"$imgsizegroup\" border=\"0\" height=\"$imgsizegroup\" src=\"$gfx\" /></a></td>\t" .
			"<td><a href=\"".$_SERVER['PHP_SELF'].'?'.($isAdmin?'f=view&cat=items&':'').'marketgroup='.$l['marketGroupID'].'&hastypes='.$l['hasTypes']."\">".$l['marketGroupName']."</a></td>\t" .
			"<td>".$l['description']."</td>\t";
        if($isAdmin) {
            $r .= "<td><form method=\"GET\" action=\"".$_SERVER['PHP_SELF']."\">".generateHiddenFields(array('marketgroup'=>$marketGroup,'hastypes'=>0,'id'=>$l['marketGroupID'],'updatemarketpricemod'=>1))."<input type=\"text\" size=\"4\" name=\"newmod\" value=\"".$l['priceMod']."\" /><input type=\"submit\" value=\"Update\" /></form></td>\t";
            $r .= "<td>".($l['isBuildable']?'<font color="green">Buildable</font>':'<font color="red">Un-Buildable</font>')." - <a href=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=0&id=".$l['marketGroupID']."&updatebuildable=1&isbuildable=".$l['isBuildable']."\">Set to ".($l['isBuildable']?'Un-':'')."Buildable</a></td>\t";
        }
        $r.="</tr>\n";
    }
    $r.= "</table>";
    return $r;
}
function getBlueprintItemGroup($marketGroup, $isAdmin=false) {
    global $bgcolored, $imgsize, $ingame;
    if(!($marketGroup=='all') && !is_number($marketGroup)) {echo "ERROR: INVALID MARKETGROUP"; require("footer.php"); exit;}
    if($marketGroup=='all') {
        if($isAdmin) {
            $blueprints = Query("SELECT * FROM blueprints ORDER BY typeName ASC");
            $items=Query("select ccpItem.typeID,ccpItem.typeName,ccpItem.groupID,ccpItem.description,ccpItem.marketGroupID,ccpEG.icon, ".
                "items.price,items.quantityModifier,items.numAvailable,items.isBuildable,items.useMineralPrices,items.isSpecialOrderable ".
                "from ccp_invTypes as ccpItem ".
                "join blueprints on ccpItem.typeID=blueprints.typeId ". 
                "left join items on items.typeID = ccpItem.typeId ".
                "left join ccp_eveGraphics as ccpEG on ccpItem.graphicID = ccpEG.graphicID ".
                "ORDER BY ccpItem.typeName ASC");
        } else {
            $blueprints = Query("SELECT * FROM blueprints WHERE numAvailable>'0' ORDER BY typeName ASC");
            $items=Query("select ccpItem.typeID,ccpItem.typeName,ccpItem.groupID,ccpItem.description,ccpItem.marketGroupID,ccpEG.icon, ".
                "items.price,items.quantityModifier,items.numAvailable,items.isBuildable,items.useMineralPrices,items.isSpecialOrderable ".
                "from ccp_invTypes as ccpItem ".
                "join blueprints on ccpItem.typeID=blueprints.typeId ". 
                "left join items on items.typeID = ccpItem.typeId ".
                "left join ccp_eveGraphics as ccpEG on ccpItem.graphicID = ccpEG.graphicID ".
            	"WHERE blueprints.numAvailable>0 ".
                "ORDER BY ccpItem.typeName ASC");
        }

    } else {
        $blueprints = Query("SELECT * FROM blueprints WHERE marketGroupID='$marketGroup' AND numAvailable>'0' ORDER BY typeName ASC");
        if($isAdmin){
            //$items = Query("SELECT * FROM items WHERE marketGroupID='$marketGroup' ORDER BY typeName ASC");
            $items=Query("select ccpItem.typeID,ccpItem.typeName,ccpItem.groupID,ccpItem.description,ccpItem.marketGroupID,ccpEG.icon, ".
                "items.price,items.quantityModifier,items.numAvailable,items.isBuildable,items.useMineralPrices,items.isSpecialOrderable ".
                "from ccp_invTypes as ccpItem ".
                "join blueprints on ccpItem.typeID=blueprints.typeId ". 
                "left join items on items.typeID = ccpItem.typeId ".
                "left join ccp_eveGraphics as ccpEG on ccpItem.graphicID = ccpEG.graphicID ".
                "WHERE ccpItem.marketGroupID='$marketGroup' ".
                "ORDER BY ccpItem.typeName ASC");
        } else {
            //$items=Query("SELECT items.* FROM items,blueprints WHERE items.typeID=blueprints.typeID AND blueprints.marketGroupID='$marketGroup' AND blueprints.numAvailable>0 ORDER BY typeName ASC");
            $items=Query("select ccpItem.typeID,ccpItem.typeName,ccpItem.groupID,ccpItem.description,ccpItem.marketGroupID,ccpEG.icon, ".
                "items.price,items.quantityModifier,items.numAvailable,items.isBuildable,items.useMineralPrices,items.isSpecialOrderable ".
                "from ccp_invTypes as ccpItem ".
                "join blueprints on ccpItem.typeID=blueprints.typeId ". 
                "left join items on items.typeID = ccpItem.typeId ".
                "left join ccp_eveGraphics as ccpEG on ccpItem.graphicID = ccpEG.graphicID ".
            	"WHERE blueprints.numAvailable>0 ".
            	"AND blueprints.marketGroupID='$marketGroup' ".
                "ORDER BY ccpItem.typeName ASC");
        }
        
    }
    if(!mysql_num_rows($items)) return "No blueprints are available in this category!<br />\n";
    //$r= "<table border=0 cellspacing=0 cellpadding=2><tr><td></td><td><b>Name</b></td><td><b>Description</b></td><td><b>Price</b></td><td></td></tr>\n";
    $r= "<table border=0 cellspacing=0 cellpadding=2><tr><td></td><td><b>Name</b></td><td><b>ME</b></td><td><b>PE</b></td><td><b>Runs</b></td><td><b>Price</b></td><td><b>Availability</b></td><td><b>Quantity</b></td>";
    if($isAdmin&&$marketGroup=='all') $r.="<td></td>";
    $r.="</tr>\n";
    while ($l = mysql_fetch_array($items, MYSQL_ASSOC)) {
        if(!$isAdmin || $marketGroup=='all') $lb = mysql_fetch_array($blueprints, MYSQL_ASSOC);
        if($l['typeID']!=$l['typeID'] && (!$isAdmin || $marketGroup=='all')) { echo "ERROR: TYPEIDs DO NOT MATCH FOR BP, ITEM ON BP ID#".$lb['id']; return false; }
        //$gfx=getGraphicPath($l['graphicID']);
        //if($ingame) $gfx='typeicon:'.$l['typeID'];
        $typeID=$l['typeID'];
		$gfx=getGraphicPath($typeID);
		$imgsize=getImgsize($typeID);
        if($isAdmin) $r.="<form method=\"GET\" action=\"".$_SERVER['PHP_SELF']."\">";
        if($isAdmin && $marketGroup!='all') $r.=generateHiddenFields(array("typeid"=>$l['typeID'],"addblueprint"=>1));
        $r.=($bgcolored?"<tr class=\"itemtablecolor1\">":"<tr class=\"itemtablecolor2\">"); $bgcolored= !$bgcolored;
        if($isAdmin && $marketGroup=='all') $r.=generateHiddenFields(array("id"=>$lb['id'], "typeid"=>$l['typeID'],"updateblueprint"=>1));
        $r .= 	"<!--ID: ".$l['typeID']."-->\t" .
			"<td width=\"$imgsize\"><img width=\"$imgsize\" height=\"$imgsize\" src=\"$gfx\" /></td>\t" .
			"<td width=\"150\">".($ingame?'<a href="javascript:CCPEVE.showInfo('.$l['typeID'].')">':'').$l['typeName'].($ingame?'</a>':'')."</td>\t";

        if($isAdmin && $marketGroup!='all') $r .= "<td><input type=\"text\" size=\"4\" name=\"me\" value=\"0\" /></td>\t";
        else if($isAdmin && $marketGroup=='all') $r .= "<td><input type=\"text\" size=\"4\" name=\"me\" value=\"".$lb['ME']."\" /></td>\t";
        else $r.="<td width=\"50\">".$lb['ME']."</td>\t";

        if($isAdmin && $marketGroup!='all') $r .= "<td><input type=\"text\" size=\"4\" name=\"pe\" value=\"0\" /></td>\t";
        else if($isAdmin && $marketGroup=='all') $r .= "<td><input type=\"text\" size=\"4\" name=\"pe\" value=\"".$lb['PE']."\" /></td>\t";
        else $r.="<td width=\"50\">".$lb['PE']."</td>\t";

        if($isAdmin && $marketGroup!='all') $r .= "<td><input type=\"text\" size=\"4\" name=\"runs\" value=\"0\" /></td>\t";
        else if($isAdmin && $marketGroup=='all') $r .= "<td><input type=\"text\" size=\"4\" name=\"runs\" value=\"".$lb['runs']."\" /></td>\t";
        else $r.="<td width=\"50\">".addCommas($lb['runs'])."</td>\t";

        if($isAdmin && $marketGroup!='all') $r .= "<td><input type=\"text\" size=\"12\" name=\"price\" value=\"".$l['price']."\" /></td>\t";
        else if($isAdmin && $marketGroup=='all') $r .= "<td><input type=\"text\" size=\"12\" name=\"price\" value=\"".$lb['price']."\" /></td>\t";
        else $r.="<td width=\"90\">".addCommas($lb['price'])."</td>\t";

        if($isAdmin && $marketGroup!='all') $r .= "<td><input type=\"text\" size=\"5\" name=\"numavailable\" value=\"0\" /></td>\t";
        else if($isAdmin && $marketGroup=='all') $r .= "<td><input type=\"text\" size=\"5\" name=\"numavailable\" value=\"".$lb['numAvailable']."\" /></td>\t";
        else $r.="<td width=\"90\">".addCommas($lb['numAvailable'])."</td>\t";

        if($isAdmin) $r .= "<td><input type=\"submit\" value=\"".($marketGroup=='all'?'Update':'Add')." Blueprint\" /></td>\t";
        else $r .= "<td><form method=\"POST\" action=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=1\">".generateHiddenFields(array("marketgroup"=>$marketGroup,"hastypes"=>1,"f"=>"cart","id"=>$lb['id']))."<input type=\"text\" size=\"4\" name=\"quantity\" value=\"1\" /><input type=\"submit\" value=\"Add to cart\" /></form></td>\t";

        if($isAdmin && $marketGroup!='all') $r.="</form></tr>\n";
        else if($isAdmin&&$marketGroup=='all') $r.="</form><td>".generateButton("Delete", "GET", array("f"=>"delete","cat"=>"blueprints","id"=>$lb['id']))."</td></tr>\t";
        else $r .= "</tr>\n";
    }
    $r.="</table>\n";
    return $r;
}
function getItemGroup($marketGroup, $isAdmin=false) {
    global $bgcolored, $imgsize, $ingame, $userLevel, $uidnum;
    $blueprintOptions=($userLevel=='producer' || $userLevel=='producertrader' || $userLevel=='admin' || $userLevel=='headproducer');
    if(!is_number($marketGroup)) {echo "ERROR: INVALID MARKETGROUP"; require("footer.php"); exit;}
    if($isAdmin){
        $items = Query("select ccpItem.typeID,ccpItem.typeName,ccpItem.groupID,ccpItem.description,ccpItem.marketGroupID,ccpEG.icon, ".
            "items.price,items.quantityModifier,items.numAvailable,items.isBuildable,items.useMineralPrices,items.isSpecialOrderable ".
            "from ccp_invTypes as ccpItem ".
            "left join items on items.typeID = ccpItem.typeId ".
            "left join ccp_eveGraphics as ccpEG on ccpItem.graphicID = ccpEG.graphicID ".
            "where ccpItem.marketGroupId = '$marketGroup' ".
            "ORDER BY typeName ASC");
    } else {
        $items = Query("select ccpItem.typeID,ccpItem.typeName,ccpItem.groupID,ccpItem.description,ccpItem.marketGroupID,ccpEG.icon, ".
            "items.price,items.quantityModifier,items.numAvailable,items.isBuildable,items.useMineralPrices,items.isSpecialOrderable ".
            "from ccp_invTypes as ccpItem ".
            "left join items on items.typeID = ccpItem.typeId ".
            "left join ccp_eveGraphics as ccpEG on ccpItem.graphicID = ccpEG.graphicID ".
            "where ccpItem.marketGroupId = '$marketGroup' AND numAvailable>='0' ".
            "ORDER BY typeName ASC");
    }
    //else $items = Query("SELECT * FROM items WHERE marketGroupID='$marketGroup' AND (numAvailable>'0' OR isSpecialOrderable='1' OR isBuildable='1') ORDER BY typeName ASC");
    if(!mysql_num_rows($items)) return "No items are available in this category!<br />\n";
    $r='';
    $i=0;
    if($isAdmin) $r.="<form method=\"POST\" action=\"".$_SERVER['PHP_SELF']."\"><table border=0 cellspacing=0 cellpadding=2><tr><td></td><td><b>Name</b></td><td><b>Price</b></td><td><b>Availability</b></td><td><b>Buildable?</b></td><td><b>Use Min Prices?</b></td><td><b>Special Orderable?</b></td></tr>\n";
    else $r.= "<table border=0 cellspacing=0 cellpadding=2><tr><td></td><td><b>Name</b></td><td><b>Price</b></td><td><b>Availability</b></td><td><b>Quantity</b></td>".($blueprintOptions?"<td><b>Options</b></td>":'')."</tr>\n";
    while ($l = mysql_fetch_array($items, MYSQL_ASSOC)) {
        $typeID=$l['typeID'];
		$gfx=getGraphicPath($typeID);
		$imgsize=getImgsize($typeID);
        $r.=($bgcolored?"<tr class=\"itemtablecolor1\">":"<tr class=\"itemtablecolor2\">"); $bgcolored= !$bgcolored;
        $r .= 	"<!--ID: ".$l['typeID']."-->\t" .
			"<td width=\"$imgsize\"><img width=\"$imgsize\" height=\"$imgsize\" src=\"$gfx\" /></td>\t" .
			"<td width=\"150\">".($ingame?'<a href="javascript:CCPEVE.showInfo('.$l['typeID'].')">':'').$l['typeName'].($ingame?'</a>':'')."</td>\t";

        if($isAdmin) $r.=generateHiddenFields(array($i."_typeid"=>$l['typeID']));

        if($isAdmin) $r .= "<td><input type=\"text\" size=\"10\" name=\"".$i."_price\" value=\"".$l['price']."\" /> Per <input type=\"text\" size=\"5\" name=\"".$i."_quantitymodifier\" value=\"".$l['quantityModifier']."\" /></td>\t";
        else $r.="<td width=\"125\">".addCommas($l['price'])." per ".addCommas($l['quantityModifier'])."</td>\t";

        if($isAdmin) $r .= "<td><input type=\"text\" size=\"5\" name=\"".$i."_availability\" value=\"".$l['numAvailable']."\" /></td>\t";
        else {
            $r.="<td width=\"125\">";
            $r.= displayAvailability($l['numAvailable'],$l['isBuildable'],$l['isSpecialOrderable']);/*
            if($l['numAvailable']<=0 && $l['isBuildable']==0) $r.= '<font color="red">Out of Stock</font>';
            else if($l['numAvailable']>0) $r.='<font color="green">In Stock:</font> <b>'.addCommas($l['numAvailable']).'</b><br />'.($l['isBuildable']?'Buildable':'<font color="red">Not Buildable</font>');
            else $r.='Built on Demand';*/
            $r.="</td>\t";
        }

        //if($isAdmin) $r .= "<td>".($l['isBuildable']?'<font color="green">Buildable</font>':'<font color="red">Un-Buildable</font>')." - <a href=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=1&id=".$l['typeID']."&updatebuildable=1&isbuildable=".$l['isBuildable']."\">Set to ".($l['isBuildable']?'Un-':'')."Buildable</a></td>\t";
        if($isAdmin) $r .= "<td><input type=\"checkbox\" name=\"isbuildable[]\" value=\"$i\" ".($l['isBuildable']?'checked ':'')." /></td>\t";
        //else $r .= "<td><a href=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=1&cart=1&id=".$l['typeID']."&name=".str_replace(" ", "+",$l['typeName'])."&price=".$l['price']."\">Add to cart</a></td>\t";
        else {
            if($l['numAvailable']<=0 && $l['isBuildable']==0 && $l['isSpecialOrderable']==0) {$r.="<td width=\"150\"></td>";}
            else if($l['numAvailable']<=0 && $l['isBuildable']==0)  {
                $r .= "<td width=\"150\"><form method=\"POST\" action=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=1\">" .
                generateHiddenFields(array("marketgroup"=>$marketGroup, "hastypes"=>"1", "cart"=>1, "specialorder"=>1, "id"=>$l['typeID'], "name"=>str_replace(" ", "_",$l['typeName']), "price"=>$l['price'])) .
					"<input type=\"text\" name=\"qty\" size=\"6\" value=\"1\" />".($l['quantityModifier']==1?'':"x".addCommas($l['quantityModifier']))."<input type=\"submit\" value=\"Special Order\" /></form></td>\t";
            }
            else $r .= "<td align=\"left\" width=\"150\"><form method=\"POST\" action=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=1\">" .
            generateHiddenFields(array("marketgroup"=>$marketGroup, "hastypes"=>"1", "cart"=>1, "id"=>$l['typeID'], "name"=>str_replace(" ", "_",$l['typeName']), "price"=>$l['price'])) .
				"<input type=\"text\" name=\"qty\" size=\"6\" value=\"1\" />".($l['quantityModifier']==1?'':"x".addCommas($l['quantityModifier']))."<input type=\"submit\" value=\"Add to cart\" /></form></td>\t";
        }
        if($blueprintOptions && !$isAdmin) {
            $hasBP=mysql_num_rows(Query("SELECT * FROM producerblueprints WHERE typeID=".$l['typeID']." AND producerID=$uidnum LIMIT 1"));
            $r.="<td width=\"175\"><a href=\"browse.php?f=".($hasBP?'remove':'add')."bp&marketgroup=$marketGroup&hastypes=1&typeid=".$l['typeID']."\">".($hasBP?'Remove from':'Add to')." BP library</a></td>";
        }
        //if($isAdmin) $r .= "<td>".($l['useMineralPrices']?'<font color="green">USING MINERAL PRICES</font>':'<font color="red">NOT USING MINERAL PRICES</font>')." - <a href=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=1&id=".$l['typeID']."&updateusemineralprices=1&usemineralprices=".$l['useMineralPrices']."\">Set to ".($l['useMineralPrices']?'NOT ':'')."USE</a></td>\t";
        if($isAdmin) $r .= "<td><input type=\"checkbox\" name=\"usemineralprices[]\" value=\"$i\" ".($l['useMineralPrices']?'checked ':'')." /></td>\t";
        if($isAdmin) $r .= "<td><input type=\"checkbox\" name=\"isspecialorderable[]\" value=\"$i\" ".($l['isSpecialOrderable']?'checked ':'')." /></td>\t";

        $r .= "</tr>\n";
        $i++;
    }
    $r.="</table>\n";
    if($isAdmin) $r .= generateHiddenFields(array("updateitemsall"=>1, "numrows"=>$i, "marketgroup"=>$marketGroup, "hastypes"=>1))."<input type=\"submit\" value=\"Update all editable fields above\" /></form>";
    if($isAdmin) $r .= "<a href=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=1&id=all&updatebuildable=1&isbuildable=0\">Set all items to <font color=\"red\">Un-Buildable</font></a> | <a href=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=1&id=all&updatebuildable=1&isbuildable=1\">Set all items to <font color=\"green\">Buildable</font></a><br />\n";
    if($isAdmin) $r .= "<a href=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=1&id=all&updateusemineralprices=1&usemineralprices=0\">Set all items to <font color=\"red\"><b>NOT</b> USE MINERAL PRICE UPDATES</font></a> | <a href=\"".$_SERVER['PHP_SELF']."?marketgroup=$marketGroup&hastypes=1&id=all&updateusemineralprices=1&usemineralprices=1\">Set all items to <font color=\"green\">USE MINERAL PRICE UPDATES</font></a>\n";
    return $r;
}

//Return an item resultset for a single item id
function getItemById ($typeID) {
    $item = Query("select ccpItem.typeID,ccpItem.typeName,ccpItem.groupID,ccpItem.description,ccpItem.marketGroupID,ccpEG.icon, ".
        "items.price,items.quantityModifier,items.numAvailable,items.isBuildable,items.useMineralPrices,items.isSpecialOrderable ".
        "from ccp_invTypes as ccpItem ".
        "left join items on items.typeID = ccpItem.typeId ".
        "left join ccp_eveGraphics as ccpEG on ccpItem.graphicID = ccpEG.graphicID ".
        "where ccpItem.typeId = '$typeID' ".
        "LIMIT 1");
    return $item;    
   
}

function getItemsByIdQueryList ($queryList) {
    $query= "select ccpItem.typeID,ccpItem.typeName,ccpItem.groupID,ccpItem.description,ccpItem.marketGroupID,ccpEG.icon, ".
        "items.price,items.quantityModifier,items.numAvailable,items.isBuildable,items.useMineralPrices,items.isSpecialOrderable ".
        "from ccp_invTypes as ccpItem ".
        "left join items on items.typeID = ccpItem.typeId ".
        "left join ccp_eveGraphics as ccpEG on ccpItem.graphicID = ccpEG.graphicID ".
        "where ccpItem.typeId = ".$queryList ." ".
        "ORDER BY typeName ASC ";
    $item = Query($query);
    return $item;    
   
}

function getItemsByProducerId ($producerId){
    $query= "select ccpItem.typeID,ccpItem.typeName,ccpItem.groupID,ccpItem.description,ccpItem.marketGroupID,ccpEG.icon, ".
        "items.price,items.quantityModifier,items.numAvailable,items.isBuildable,items.useMineralPrices,items.isSpecialOrderable ".
        "from ccp_invTypes as ccpItem ".
        "left join items on items.typeID = ccpItem.typeId ".
        "left join ccp_eveGraphics as ccpEG on ccpItem.graphicID = ccpEG.graphicID ".
        "where ccpItem.typeId IN (SELECT `typeID` FROM producerblueprints WHERE producerID=$producerId) ORDER BY typeName ASC";
    $items = Query($query);
    return $items;    
}

//Return a marketgroup by id
function getMarketGroupById ($marketGroupId){
    $mg = Query("SELECT ccpIMG.marketGroupID,ccpIMG.parentGroupID,ccpIMG.marketGroupName,ccpIMG.description,ccpEG.icon,ccpIMG.hasTypes,tgIMG.isBuildable,tgIMG.priceMod ".
			"FROM ccp_invMarketGroups as ccpIMG " .
			"left join invMarketGroups as tgIMG on tgIMG.marketGroupID = ccpIMG.marketGroupID ".
			"left join ccp_eveGraphics as ccpEG on ccpIMG.graphicID = ccpEG.graphicID ".
        	"WHERE ccpIMG.marketGroupID='$marketGroupId' LIMIT 1");
    return $mg;
}

//Return all items whose name contains a certain string
function searchItemsBySubString($searchString) {
    $items =  Query("select ccpItem.typeID,ccpItem.typeName,ccpItem.groupID,ccpItem.description,ccpItem.marketGroupID,ccpEG.icon, ".
        "items.price,items.quantityModifier,items.numAvailable,items.isBuildable,items.useMineralPrices,items.isSpecialOrderable ".
        "from ccp_invTypes as ccpItem ".
        "left join items on items.typeID = ccpItem.typeId ".
        "left join ccp_eveGraphics as ccpEG on ccpItem.graphicID = ccpEG.graphicID ".
        "where  ccpItem.marketGroupID IS NOT NULL AND ccpItem.typeName LIKE '%".$searchString."%' AND numAvailable>='0' ".
    	"ORDER BY ccpItem.typeName ASC");
    return $items;
}

//Returns an array of form "34"=>"1000042" or, if arg is set, "Megacyte"=>"23652"
function getMineralCosts ($typeID, $quantity=1, $useNames=false) {
    $mincosts = Query("SELECT * FROM ccp_typeActivityMaterials WHERE activityID=1 AND typeID='$typeID' AND ((requiredTypeID<=40 AND requiredTypeID>=34) OR requiredTypeID=11399) ORDER BY quantity DESC LIMIT 8");
    $r=array();
    while($l=mysql_fetch_array($mincosts)) {
        if($useNames) {
            $key=mysql_result(Query("SELECT * FROM ccp_invTypes WHERE typeID='".$l['requiredTypeID']."' LIMIT 1"),0,'typeName');
        } else $key=$l['requiredTypeID'];
        $r[$key]=$l['quantity']*1.1*$quantity;
        //echo "-- $key - $r[$key]--\n";
    }
    if(empty($r)) return false;
    return $r;
}
function getBasePrice ($typeID, $quantity=1) {
    $mc = getMineralCosts($typeID, $quantity);
    if(!$mc) return false;
    $total=0;
    foreach($mc as $key=>$qty) {
        //DO NOT FIX This is just selecting the price of the item.  This will be the cost of the mins to build the item.
        $total+= (mysql_result(Query("SELECT price FROM items WHERE typeID='$key' LIMIT 1"),0,'price') * $qty);
    }
    return $total * $quantity;
}
//Returns true if successful, false if orders do not in fact match
function combineOrders($id1, $id2) {
    $orders = Query("SELECT * FROM orders WHERE id='$id1' OR id='$id2' LIMIT 2");
    $order1=mysql_fetch_array($orders);
    $order2=mysql_fetch_array($orders);
    $usingStock ='';
    if(
    $order1['customerID']===$order2['customerID'] &&
    $order1['status']===$order2['status'] &&
    $order1['timePlaced']===$order2['timePlaced'] &&
    $order1['typeID']===$order2['typeID']
    ) { //MATCH
        if($order1['status']=='in cart' && $order1['usingStock'] !== $order2['usingStock']) { //SPECIAL CHECK: can do iff one is specialorder one is stockorder - combines both to stockorder iff in cart
            if(($order1['usingStock']==0 && $order2['usingStock']==2)) {
                $usingStock=', usingStock=0';
            } else if(($order1['usingStock']==2 && $order2['usingStock']==0)) {
                $usingStock=', usingStock=0';
            } else return false;
        }
        $resultUpdate = Query("UPDATE orders SET quantity=quantity+".$order2['quantity'].", priceTotal=quantity*pricePerUnit$usingStock WHERE id='".$order1['id']."' LIMIT 1");
        $resultDelete = Query("DELETE FROM orders WHERE id='".$order2['id']."' LIMIT 1");
        return true;
    } else return false;
}
//Takes an order's usingStock value, returns a text version of its type
function getUncoloredType($usingStock) {
    switch ($usingStock) {
        case 0:
            return "Build";
        case 1:
            return "Stock";
        case 2:
            return "Special";
        case 3:
            return "Blueprint";
    }
    return "INVALID usingStock VALUE";
}
//As getType, but with colorization
function getColoredType($usingStock) {
    switch ($usingStock) {
        case 0:
            return "Build";
        case 1:
            return "<font color=\"#77FFAA\">Stock</font>";
        case 2:
            return "<font color=\"#FFFF00\">Special</font>";
        case 3:
            return "<font color=\"#77AAFF\">Blueprint</font>";
    }
    return "INVALID usingStock VALUE";
}
function dateTime($syntax,$datetime) {
    if(empty($datetime)) return '';
    global $serverTimeZone, $eveTimeZone;
    $year = substr($datetime,0,4);
    $month = substr($datetime,5,2);
    $day = substr($datetime,8,2);
    $hour = substr($datetime,11,2) - $serverTimeZone + $eveTimeZone;
    $min = substr($datetime,14,2);
    $sec = substr($datetime,17,2);
     
    return date($syntax,mktime($hour,$min,$sec,$month,$day,$year));
}
function evemail($name, $subject=null, $message=null, $linktext=null) {
    global $ingame;
    $defaultSubject = "TGRAD Order: Status Update";
    $name=ucwords($name);
    if(empty($linktext)) $linktext=$name;
    if(!$ingame) return $linktext;
    if(empty($subject) && isset($defaultSubject)) $subject=$defaultSubject;
    if(empty($subject) && empty($message)) {
        return "<a href=\"evemail:$name\">$linktext</a>";
    } else {
        $message=str_replace("\"", "'", $message);
        $subject=str_replace("\"", "'", $subject);
        return "<a href=\"evemailto:$name\" subject=\"$subject\" message=\"$message\">$linktext</a>";
    }
}
function itemListToArray($itemlist) { //Takes itemlist of format typeIDxqty,typeIDxqty,typeID... and returns array(typeID=>qty, typeID=>qty, ...)
    $ta = explode(',',$itemlist);
    foreach($ta as $v) {
        $tai=explode('x',$v);
        $itemarray[$tai[0]]=$tai[1];
    }
    return $itemarray;
}
function itemArrayToList($itemarray) { //reverse of above
    $i=0;
    foreach($itemarray as $k=>$v) {
        $ta[$i]=$k.'x'.$v;
        $i++;
    }
    return implode(',',$ta);
}
function itemArrayToQueryList($itemarray) {
    $i=0;
    foreach($itemarray as $k=>$v) {
        $ta[$i]=$k;
        $i++;
    }
    return implode(" OR ccpItem.typeID=", $ta);
}
?>
